package com.jmx.mstcodesandbox.utils;

import cn.hutool.core.io.IoUtil;
import com.jmx.mstcodesandbox.model.ProcessInfo;
import org.springframework.util.StopWatch;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

import static com.jmx.mstcodesandbox.javasandbox.JavaNativeCodeSandBox.EXEC_TIME_OUT;

/**
 * 运行cmd命令行工具类
 */
public class ProcessUtil {
    public static ProcessInfo executeCmd(String cmd, Charset charset){
        ProcessInfo processInfo = new ProcessInfo();
        try {
            Process process = Runtime.getRuntime().exec(cmd);
            //限制程序执行时间
            new Thread(()->{
                try {
                    Thread.sleep(EXEC_TIME_OUT);
                    process.destroy();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }).start();
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            int exitValue = process.waitFor();
            stopWatch.stop();
            processInfo.setCode(exitValue);
            processInfo.setTime(stopWatch.getLastTaskTimeMillis());
            String message;
            // 正常执行退出
            if (exitValue == 0) {
                // 获取该输入流的所有内容
                message = IoUtil.read(process.getInputStream(),charset);
            } else {
                message = IoUtil.read(process.getErrorStream(),charset);
            }
            processInfo.setMessage(message);
            return processInfo;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static ProcessInfo executeCmd(String cmd){
      return executeCmd(cmd, StandardCharsets.UTF_8);
    }
}
